﻿using AutoMapper;
using MediatR;
using Traceability.App.Api.Application.Command.Add;
using Traceability.App.Domain;
using Traceability.App.ErrorCode;
using Traceability.App.Instructure;

namespace Traceability.App.Api.Application.Handler.Add
{
    public class AddSlaughterHandler : IRequestHandler<AddSlaughterCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<SlaughterModel> slaughterRepo;
        private readonly IMapper mapper;

        public AddSlaughterHandler(IBaseRepository<SlaughterModel> slaughterRepo,IMapper mapper) 
        {
            this.slaughterRepo = slaughterRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(AddSlaughterCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var tuzai = slaughterRepo.GetAll().Where(x => x.Batch == request.Batch).FirstOrDefault();
            if (tuzai==null)
            {
                var entity = mapper.Map<SlaughterModel>(request);
                slaughterRepo.Add(entity);
            }
            else
            {
                tuzai.SlaughterDateTime = request.SlaughterDateTime;
                tuzai.AverageWeight= request.AverageWeight;
                tuzai.DaoDateTime= request.DaoDateTime;
                tuzai.UpdateTime=DateTime.Now;
                tuzai.CreateTime= DateTime.Now;
                tuzai.CreateName = "张三";
                tuzai.UpdateName = "张三";
                slaughterRepo.Update(tuzai);    
            }
            res.Code = ApiEnum.Success;
            res.Msg = "设置屠宰信息成功";
            return Task.FromResult(res);
        }
    }
}
